<template>
  <el-container>
    <BomTree style="margin-top: 16px" @on-choose-region="filetrStation" />
    <el-main>
      <div class="default-main ba-table-box">
        <!-- 表格顶部菜单 -->
        <TableHeader
          :buttons="[
            'refresh',
            'add',
            'edit',
            'remove',
            'comSearch',
            'columnDisplay',
          ]"
          :quick-search-placeholder="placeholder"
          @action="baTable.onTableHeaderAction"
        />
        <!-- 要使用`el-table`组件原有的属性，直接加在Table标签上即可 -->
        <Table ref="tableRef" @action="baTable.onTableAction" />
        <!-- 表单 -->
        <PopupForm
          v-if="
            (baTable.form.operate !== 'upload' &&
              baTable.form.operate !== 'info' &&
              JSON.stringify(purchase.purchaseMaterialInfo) !== '{}' &&
              baTable.form.operate) ||
            baTable.form.operate === 'edit'
          "
        />
        <Info
          v-if="
            baTable.form.operate !== 'edit' && baTable.form.operate !== 'add'
          "
        />
      </div>
    </el-main>
  </el-container>
</template>
<script lang="ts" setup>
import {
  ref,
  provide,
  onMounted,
  markRaw,
  reactive,
  onBeforeUnmount,
} from "vue";
import baTableClass from "@/utils/baTable";
import {
  baTableApi,
  operatorShowOff,
  getDictData,
  buildJsonToElTreeData,
} from "@/utils/common"; // 导入表格api方法生成器
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import { StoreWarePurchase } from "@/api/backend/index";
import { useRoute, useRouter } from "vue-router";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { useNavTabs } from "@/store/navTabs";
import PopupForm from "./popupForm.vue";
import { useDictionary } from "@/store/backend/tool/dictionary";
import { useBomM } from "@/store/backend/BomM/bomM";
import _ from "lodash";
import Info from "./info.vue";
import { useStoreWarehouseLocation } from "@/store/backend/StoreroomM/Location";
import BomTree from "./components/aside.vue";
import { useStoreWarePurchase } from "@/store/backend/StoreroomM/Purchase";
import { useUser } from "@/store/backend/SysM/user";
import { useAdminInfo } from "@/store/adminInfo";
import { useSupplierInfo } from "@/store/backend/Supplier/Info";
import { useSupplierChain } from "@/store/backend/Supplier/Chain";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const placeholder = ref<string>(t("storeroom.purchase.模糊搜索"));
const tableRef = ref();
const route = useRoute();
const router = useRouter();
const navTabs = useNavTabs();
const dictionary = useDictionary();
const Location = useStoreWarehouseLocation();
const bom = useBomM();
const purchase = useStoreWarePurchase();
const User = useUser();
const adminInfo = useAdminInfo();
const supplier = useSupplierInfo();
const chain = useSupplierChain();

//全局事件总线
const { proxy } = useCurrentInstance();
const state: {} = reactive({});

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + StoreWarePurchase)
      ? (navTabs as any).pageSizeMap.get(route.path + StoreWarePurchase)
      : 10;
  }
  return 10;
};

const baTable = new baTableClass(
  new baTableApi(StoreWarePurchase), //this.api = api部门管理
  {
    expandAll: true,
    pk: "purchaseListId",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("purchaseListId"),
        label: t("storeroom.purchase.采购单号"),
        prop: "purchaseListId",
        align: "left",
        operatorPlaceholder: t("storeroom.purchase.模糊搜索"),
      },
      {
        show: filedShowOff("materialName"),
        label: t("storeroom.purchase.物料名称"),
        prop: "materialName",
        align: "left",
        operatorPlaceholder: t("storeroom.purchase.模糊搜索"),
      },
      {
        show: filedShowOff("materialCode"),
        label: t("storeroom.purchase.物料编号"),
        prop: "materialCode",
        align: "left",
        operatorPlaceholder: t("storeroom.purchase.模糊搜索"),
      },
      {
        show: filedShowOff("materialType"),
        label: t("storeroom.purchase.物料型号"),
        prop: "materialType",
        align: "left",
        operatorPlaceholder: t("storeroom.purchase.模糊搜索"),
      },
      {
        show: filedShowOff("purchaseQuantity"),
        label: t("storeroom.purchase.采购数量"),
        prop: "purchaseQuantity",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("unit"),
        label: t("storeroom.purchase.单位"),
        prop: "unit",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("taxUnitPrice"),
        label: t("storeroom.purchase.含税单价"),
        prop: "taxUnitPrice",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("taxTotalPrice"),
        label: t("storeroom.purchase.含税总价"),
        prop: "taxTotalPrice",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("unitPriceWithoutTax"),
        label: t("storeroom.purchase.未含税单价"),
        prop: "unitPriceWithoutTax",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("supplierName"),
        label: t("storeroom.purchase.供应商名称"),
        prop: "supplierName",
        align: "center",
        operator: false,
      },
      {
        show: filedShowOff("operatorTime"),
        label: t("storeroom.purchase.操作时间"),
        prop: "operatorTime",
        align: "center",
        operator: false,
      },

      {
        show: operatorShowOff([
          route.path + "/edit",
          route.path + "/add",
          route.path + "/remove",
        ]),
        label: t("storeroom.purchase.操作"),
        align: "center",
        operator: false,
        render: "buttons",
        fixed: "right",
        width: "150",
        buttons: [
          {
            render: "tipButton",
            name: "info",
            title: t("storeroom.purchase.详情"),
            text: "",
            type: "primary",
            icon: "iconfont icon-chaxunyujisuan",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
          {
            render: "tipButton",
            name: "edit",
            title: t("storeroom.purchase.编辑"),
            text: "",
            type: "primary",
            icon: "iconfont icon-pencil",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
    },
    extend: {
      maxHeight: 580,
    },
  },
  {
    defaultItems: { parentId: 0, parentCode: "0" },
  },
  {}
);

//获取采购单状态/结算方式/开票方式字典
const getMenuStatus = () => {
  //采购单状态
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["purchaseStatusCode"])
  ) {
    dictionary.getDictInfo("sys_purchase_status").then((res: any) => {
      dictionary.moreTags["purchaseStatusCode"] = getDictData(res);
      dictionary.moreTags["purchaseStatusCodeOrigin"] = res;
    });
  }
  //采购单结算方式
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["settlementMethod"])
  ) {
    dictionary.getDictInfo("sys_purchase_settlement").then((res: any) => {
      dictionary.moreTags["settlementMethod"] = getDictData(res);
      dictionary.moreTags["settlementMethodOrigin"] = res;
    });
  }
  //开票方式
  if (
    JSON.stringify(dictionary.moreTags) == "{}" ||
    !JSON.stringify(dictionary.moreTags["billingMethod"])
  ) {
    dictionary.getDictInfo("sys_purchase_billing").then((res: any) => {
      dictionary.moreTags["billingMethod"] = getDictData(res);
      dictionary.moreTags["billingMethodOrigin"] = res;
    });
  }
};
//获取采购单状态/结算方式/开票方式字典
getMenuStatus();

//接收工作中心树传递过来的数据
const filetrStation = (row: any, node: any) => {
  console.log("接收bom树传递过来的数据");

  if (node.checkedKeys.length == 0) {
    //表示取消选择直接调用刷新表单方法
    baTable.comSearch.form;
    baTable.comSearch.form = {
      materialName: "",
      materialCode: "",
      materialType: "",
      materialRecordType: "",
      purpose: "",
      pageSize: 10,
    };
    baTable.onTableHeaderAction("refresh", {});
    purchase.$patch((state: any) => {
      state.purchaseMaterialInfo = {};
    });
  } else {
    baTable.comSearch.form.materialCode = row.code; //过滤参数 物料编号
    baTable.comSearch.form.materialType = row.type; //过滤参数 物料型号
    if (node.halfCheckedNodes.length > 0) {
      // baTable.comSearch.form.parentCode = node.halfCheckedNodes[0].code;
      //如果有父级node就保存起来
      purchase.$patch((state: any) => {
        state.bomTreeParent = node.halfCheckedNodes[0];
      });
    } else {
      baTable.comSearch.form.parentCode = "";
      purchase.$patch((state: any) => {
        state.purchaseMaterialInfo = {};
      });
    }
    baTable.getList(StoreWarePurchase);
    purchase.$patch((state: any) => {
      state.purchaseMaterialInfo = row;
    });
  }
};

/** 点击查看详情按钮响应 */
const infoButtonClick = (row: TableRow) => {
  if (!row) return;
  // 数据来自表格数据,未重新请求api,深克隆,不然可能会影响表格
  let rowClone = _.cloneDeep(row);
  rowClone.operParam = rowClone.operParam
    ? [
        {
          label: "点击展开",
          children: buildJsonToElTreeData(JSON.parse(rowClone.operParam)),
        },
      ]
    : [];

  baTable.form.extend!["info"] = rowClone;
  console.log("点击查看详情按钮响应", rowClone);

  baTable.form.operate = "info";
};

onMounted(() => {
  //全局事件总线
  const { proxy } = useCurrentInstance();
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(StoreWarePurchase);
  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */

  proxy.eventBus.on(
    "onTableButtonClick",
    (data: { name: string; row: TableRow }) => {
      if (!baTable.activate) return;
      if (data.name == "info") {
        infoButtonClick(data.row);
      }
    }
  );
});

onBeforeUnmount(() => {
  purchase.$patch((state: any) => {
    state.purchaseMaterialInfo = {};
  });
});
// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);
provide("dictionary", dictionary);
provide("Location", Location);
provide("bom", bom);
provide("purchase", purchase);
provide("User", User);
provide("adminInfo", adminInfo);
provide("supplier", supplier);
provide("chain", chain);
</script>
<style lang="scss" scoped>
.default-main {
  margin: 0px !important;
}
</style>
